package com.example.teacherservice.service;

import com.example.teacherservice.dto.*;
import com.example.teacherservice.entity.*;
import com.example.teacherservice.repository.*;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CourseDetailService {

    private final CourseRepository courseRepository;
    private final CourseDetailRepository courseDetailRepository;

    public CourseDetailDTO getCourseDetail(Long courseId, Long studentId) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("课程不存在"));

        List<Chapter> chapters = courseDetailRepository.findChaptersByCourseId(courseId);
        List<StuCourseAppraise> appraises = courseDetailRepository.findAppraisesByCourseId(courseId);

        boolean purchased = false;
        if (studentId != null) {
            try {
                int count = courseDetailRepository.countByStuIdAndCourseId(studentId, courseId);
                purchased = count > 0;
            } catch (Exception e) {
                System.err.println("检查购买状态失败: " + e.getMessage());
            }
        }

        return CourseDetailDTO.builder()
                .id(course.getId())
                .name(course.getCouName())
                .introduction(course.getCouIntroduction())
                .pictureUrl(course.getCouPic())
                .price(course.getCouPrice())
                .collectionCount(course.getCouCollNum())
                .likeCount(course.getCouLikeNum())
                .shareCount(course.getCouShareNum())
                .clicks(course.getClicks())
                .purchaseCount(course.getPurchase())
                .purchased(purchased)
                .chapters(chapters.stream()
                        .map(this::convertToChapterDTO)
                        .collect(Collectors.toList()))
                .appraises(appraises.stream()
                        .map(this::convertToAppraiseDTO)
                        .collect(Collectors.toList()))
                .build();
    }

    @Transactional
    public OrderDTO purchaseCourse(Long courseId, Long studentId) {
        try {
            // 1. 检查是否已购买
            int count = courseDetailRepository.countByStuIdAndCourseId(studentId, courseId);
            if (count > 0) {
                throw new RuntimeException("您已购买过该课程");
            }

            // 2. 获取课程信息
            Course course = courseRepository.findById(courseId)
                    .orElseThrow(() -> new RuntimeException("课程不存在"));

            // 3. 生成订单号
            String orderCode = "ORD" + System.currentTimeMillis() +
                    UUID.randomUUID().toString().substring(0, 6);

            // 4. 创建订单（添加事务回滚）
            try {
                courseDetailRepository.insertOrder(orderCode, studentId, Double.valueOf(course.getCouPrice()));
                Long orderId = courseDetailRepository.getLastInsertId();

                // 5. 创建订单详情
                courseDetailRepository.insertOrderDetail(
                        orderId,
                        courseId,
                        Double.valueOf(course.getCouPrice()),
                        course.getCouPic(),
                        course.getCouName(),
                        "" // 教师姓名
                );

                // 6. 创建学生课程关联
                courseDetailRepository.insertStuCourse(studentId, courseId);

                // 7. 更新课程购买数量
                courseDetailRepository.incrementPurchaseCount(courseId);

                return OrderDTO.builder()
                        .id(orderId)
                        .orderCode(orderCode)
                        .studentId(studentId)
                        .amount(course.getCouPrice())
                        .createTime(LocalDateTime.now())
                        .build();

            } catch (Exception e) {
                // 重要：添加事务回滚标记
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new RuntimeException("创建订单失败: " + e.getMessage());
            }

        } catch (RuntimeException e) {
            // 已知业务异常
            throw e;
        } catch (Exception e) {
            // 系统异常
            throw new RuntimeException("系统错误，请稍后再试");
        }
    }


    @Transactional
    public CourseAppraiseDTO addCourseReview(Long courseId, Long studentId, String score, String content) {
        // 1. 仅验证课程是否存在
        if (!courseRepository.existsById(courseId)) {
            throw new RuntimeException("课程不存在");
        }

        try {
            // 2. 直接插入评价（不再验证购买状态）
            courseDetailRepository.insertCourseAppraise(studentId, courseId, score, content);

            // 3. 获取新评价ID
            Long appraiseId = courseDetailRepository.getLastAppraiseId();

            // 4. 返回评价信息
            return CourseAppraiseDTO.builder()
                    .id(appraiseId)
                    .studentId(studentId)
                    .courseId(courseId)
                    .score(score)
                    .content(content)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException("评价提交失败: " + e.getMessage());
        }
    }

    public PurchaseStatusDTO checkPurchaseStatus(Long courseId, Long studentId) {
        if (studentId == null) {
            return PurchaseStatusDTO.builder()
                    .hasPurchased(false)
                    .message("未登录用户")
                    .build();
        }

        try {
            // 使用更可靠的查询
            int exists = courseDetailRepository.existsPurchase(studentId, courseId);
            boolean hasPurchased = exists == 1;

            // 调试日志
            System.out.printf("Purchase check - studentId: %d, courseId: %d, exists: %d%n",
                    studentId, courseId, exists);

            return PurchaseStatusDTO.builder()
                    .hasPurchased(hasPurchased)
                    .message(hasPurchased ? "已购买该课程" : "未购买该课程")
                    .build();
        } catch (Exception e) {
            System.err.println("检查购买状态失败: " + e.getMessage());
            return PurchaseStatusDTO.builder()
                    .hasPurchased(false)
                    .message("系统错误，无法验证购买状态")
                    .build();
        }
    }

    // 保持原有convertToChapterDTO方法完全不变
    private ChapterDTO convertToChapterDTO(Chapter chapter) {
        return ChapterDTO.builder()
                .id(chapter.getId())
                .courseId(chapter.getCourseId())  // 修正为getCourseId()
                .index(chapter.getIndex())       // 修正为getIndex()
                .title(chapter.getTitle())       // 修正为getTitle()
                .url(chapter.getUrl())           // 修正为getUrl()
                .build();
    }

    private CourseAppraiseDTO convertToAppraiseDTO(StuCourseAppraise appraise) {
        return CourseAppraiseDTO.builder()
                .id(appraise.getId())
                .studentId(appraise.getStudentId())
                .courseId(appraise.getCourseId())
                .content(appraise.getContent())
                .score(appraise.getScore())
                .build();
    }
}